// pages/category/index.js

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [],
    currCategory: [],
    activeIndex: 0,
    scrollTop: 0,
    enhanced: true,
    showScrollbar: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const Cates = wx.getStorageSync('cates');
    if (!Cates) {
      this.getCategories();
    } else {
      if (Date.now() - Cates.time > 1000 * 100 * 6) {
        console.log('重新获取');
        this.getCategories();
      } else {
        console.log('没过期');
        this.setData({
          categoryList: wx.getStorageSync('cates').data,
        });
        this.getCurrCategory();
      }
    }
  },

  getCategories() {
    app.wxRequest({
        url: '/categories',
      })
      .then((res) => {
        // 将数据存储到本地
        wx.setStorageSync('cates', {
          time: Date.now(),
          data: res.data.message,
        });
        this.setData({
          categoryList: res.data.message,
        });
        this.getCurrCategory();
      })
      .catch((err) => {
        console.log(err);
      });
  },
  go2Category(e) {
    this.setData({
      activeIndex: e.currentTarget.dataset.index,
      scrollTop: 0,
    });
    this.getCurrCategory();
  },
  getCurrCategory() {
    const currCategory = this.data.categoryList[this.data.activeIndex];
    this.setData({
      currCategory: currCategory,
    });
  },
  go2Detail(e) {
    const cid = e.currentTarget.dataset.cid;
    wx.navigateTo({
      url: '../goods_list/index?cid=' + cid,
    });
  },
  // reset() {
  //   this.setData({
  //     activeIndex: 0,
  //   });
  //   this.getCurrCategory();
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});